﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Text2String
{
    internal class ConfigFile
    {
        public bool WatchClipboard { set; get; }
        public bool AutoMinimizedAfterCopy { set; get; }

        private string filePath = Path.Combine(System.IO.Path.GetTempPath(), "Text2String." + System.Environment.UserName + ".json");

        public ConfigFile()
        {
            if(!File.Exists(this.filePath))
            {
                Reinit();
            }
            else
            {
                Read();
            }
        }

        public void Reinit()
        {
            WatchClipboard = true;
            AutoMinimizedAfterCopy = true;
            Write();
        }
        public void Write()
        {
            File.WriteAllText(filePath, JsonConvert.SerializeObject(this, Formatting.Indented));
        }
        public void Read()
        {
            // 读取 JSON 文件的内容
            // 将文件内容转换为 JToken 对象
            JObject theJsonObj = LoadJsonFile(filePath);
            if (theJsonObj == null)
            {
                Reinit();
                return;
            }
            JToken theToken = default(JToken);
            // 获取json文件里面记录的版本
            string tar = "WatchClipboard";
            if (theJsonObj.TryGetValue(tar, out theToken))
            {
                WatchClipboard = (bool)theJsonObj[tar];
            }
            else
            {
                Reinit();
                return;
            }

            tar = "AutoMinimizedAfterCopy";
            if (theJsonObj.TryGetValue(tar, out theToken))
            {
                AutoMinimizedAfterCopy = (bool)theJsonObj[tar];
            }
            else
            {
                Reinit();
                return;
            }
        }

        private JObject LoadJsonFile(string filepath)
        {
            try
            {
                // 读取 JSON 文件的内容
                string json = File.ReadAllText(filepath);

                if (json == string.Empty)
                {
                    return null;
                }
                // 将文件内容转换为 JToken 对象
                JObject data = (JObject)JToken.Parse(json);

                return data;
            }
            catch (Exception ex)
            {
                Console.WriteLine("读取 JSON 文件时发生异常: " + ex.ToString());
                return null;
            }
        }
    }
}
